//
//  UserAccount.m
//  weibo-OC
//
//  Created by diyuyma on 16/3/4.
//  Copyright © 2016年 zhangkaiyun. All rights reserved.
//

#import "UserAccount.h"

@interface UserAccount ()<NSCoding>

@end

@implementation UserAccount

- (void)setExpires_in:(NSTimeInterval)expires_in {
    _expires_in = 0;
    if (expires_in != 0) {
        _expires_in = expires_in;
        _expires_date = [NSDate dateWithTimeIntervalSinceNow:_expires_in];
    }
    
}

//KVC设置初始值
- (instancetype)initWithDict:(NSDictionary *)dict {
    //super 实例化
    self = [super init];
    [self setValuesForKeysWithDictionary:dict];
    return  self;
}

- (void)nitWithDict:(NSDictionary *)dict {
    [self setValuesForKeysWithDictionary:dict];
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

- (NSString *)description {
    
    NSArray *keys = @[@"access_token", @"expires_in", @"avatar_large", @"name", @"expires_date",@"uid"];
    
    //    NSDictionary *keys = [[NSDictionary alloc]initWithObjectsAndKeys:@"access_token", @"expires_in", @"avatar_large", @"name", @"expires_date",@"uid", nil];
    return [[self dictionaryWithValuesForKeys:keys] description];
}

- (void)saveAccount {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"account.plist"];
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}

//对外提供届归档方法
//func  是一个对象方法  函数前 加 class
- (UserAccount *)loadAccount {
    // 解归档
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"account.plist"];
    UserAccount *account = (UserAccount *)[NSKeyedUnarchiver unarchiveObjectWithFile:path];
    // 判断用户的token是否过期    
    if ([account.expires_date compare:[NSDate date]] == NSOrderedDescending) {
        return account;
    }
    return nil;
}

//MARK: 实现NSCoding 协议方法
//解归档  将 磁盘中的二进制数据 -> 转换成自定义对象  跟反序列化很像
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    if (self = [super init]) {
        _expires_date = [aDecoder decodeObjectForKey:@"expires_date"];
        _access_token = [aDecoder decodeObjectForKey:@"access_token"];
        _expires_in = [aDecoder decodeDoubleForKey:@"expires_in"];
        _uid = [aDecoder decodeObjectForKey:@"uid"];
        _name = [aDecoder decodeObjectForKey:@"name"];
        _avatar_large = [aDecoder decodeObjectForKey:@"avatar_large"];
    }
    return self;
}

//归档 将对象 转换二进制  保存到磁盘中  序列化
- (void)encodeWithCoder:(NSCoder *)aCoder {
    
    [aCoder encodeObject:_expires_date forKey:@"expires_date"];
    [aCoder encodeObject:_uid forKey:@"uid"];
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_avatar_large forKey:@"avatar_large"];
    [aCoder encodeObject:_access_token forKey:@"access_token"];
    [aCoder encodeDouble:_expires_in forKey:@"expires_in"];
}

@end
